package com.bluefeather.songlyric;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnClickListener;
import android.database.Cursor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

public class ToneActivity extends ListActivity {
	
	static private int[]		BACKGROUNDS = new int[] {
		R.drawable.music_bg1, R.drawable.music_bg2, R.drawable.music_bg3, R.drawable.music_bg4,
		R.drawable.music_bg5, R.drawable.music_bg6, R.drawable.music_bg7, R.drawable.music_bg8
	};
	
	private int					_toneIndex;
	private int					_toneType;
	private int					_background = 0;
	private ProgressDialog		_progressDialog = null;
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Bundle extras = getIntent().getExtras();
		_toneIndex = extras.getInt("TONE_INDEX");
		_toneType = extras.getInt("TONE_TYPE");
		if(_toneType == DB.TONE_TYPE_P)
			setTitle(R.string.drawer_tone_p);
		else
			setTitle(R.string.drawer_tone_z);
		setContentView(R.layout.activity_tone);
		View view = findViewById(R.id.tone_layout);
		SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(SongLyricApp.instance());
		if(sp.getBoolean("BG_PICTURE", true)) {
			_background = (int)(Math.random() * BACKGROUNDS.length);
			view.setBackgroundResource(BACKGROUNDS[_background]);
		}
		View listView = findViewById(android.R.id.list);
		listView.setOnTouchListener(new BGSwitcher());
		TextView title = (TextView)findViewById(R.id.tone_title_text);
		title.setText(DB.instance().getToneTitle(_toneIndex));
		
		Cursor c = DB.instance().getToneWords(_toneIndex, _toneType);
		String[] columns = new String[] { DB.TONEWORD._SUBJECT, DB.TONEWORD._WORDS };
		int[] ids = new int[]{ android.R.id.text1, android.R.id.text2 };
		setListAdapter(new SimpleCursorAdapter(this, R.layout.row_toneword, c, columns, ids, 0));
	}
	
	public void switchBackground() {
		if(++_background >= BACKGROUNDS.length)
			_background = -1;
		View view = findViewById(R.id.tone_layout);
		if(_background >= 0)
			view.setBackgroundResource(BACKGROUNDS[_background]);
		else
			view.setBackground(null);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.tone, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		if (id == R.id.action_about) {
			Intent i = new Intent(this, DocActivity.class);
			i.putExtra("DOC", "about");
			startActivity(i);
			return true;
		} else if(id == R.id.action_settings) {
			Intent i = new Intent(this, SettingsActivity.class);
			startActivity(i);
			return true;
		} else if(id == R.id.action_search) {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage(R.string.tone_full_search).setCancelable(false).setPositiveButton("YES",
				new OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						loadAllMusics();
					}
				
			}).setNegativeButton("NO",
				new OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						searchLyrics();
					}
				
			});
			AlertDialog dialog = builder.create();
			dialog.show();
		}
		return super.onOptionsItemSelected(item);
	}
	
	private void loadAllMusics() {
		_progressDialog = ProgressDialog.show(this, "Load", "Loading", true);
		new Thread(new Runnable() {
			@Override
			public void run()
			{
				int count = DB.instance().countMusics();
				for(int i = 1; i <= count; ++i)
					DB.instance().importMusic(i);
				runOnUiThread(new Runnable() {
					@Override
					public void run()
					{
						_progressDialog.dismiss();
						searchLyrics();
					}
				});
			}
		}).start();
	}
	
	private void searchLyrics() {
		Intent intent = new Intent(this, MusicActivity.class);
		String where = DB.LYRIC._TONE + " = " + _toneIndex;
		where += " AND " + DB.LYRIC._MUSIC + " IN ( SELECT " + DB.MUSIC._ID
			+ " FROM " + DB.MUSIC._T + " WHERE "
			+ DB.MUSIC._TONE_TYPE + " IN ( " + _toneType;
		if(_toneType == DB.TONE_TYPE_P)
			where += ", " + DB.TONE_TYPE_R;
		where += " ) )";
		intent.putExtra("LYRIC_WHERE", where);
		startActivity(intent);
	}
	
	class BGSwitcher implements OnTouchListener {

		private static final float	LYRIC_LIMIT = 200f;
		private static final float	BG_LIMIT = 50;
		
		private float			_downX = 0;
		private float			_minX = 0;
		private float			_maxX = 0;
		
		@Override
		public boolean onTouch(View v, MotionEvent event) {
			switch(event.getActionMasked()) {
			case MotionEvent.ACTION_DOWN :
				_downX = event.getX();
				_minX = _downX;
				_maxX = _downX;
				break;
			case MotionEvent.ACTION_MOVE :
				float x = event.getX();
				if(x > _maxX)
					_maxX = x;
				else if(x < _minX)
					_minX = x;
				break;
			case MotionEvent.ACTION_UP :
				float dx = event.getX() - _downX;
				if(Math.abs(dx) < BG_LIMIT && _maxX - _minX > LYRIC_LIMIT) {
					ToneActivity.this.switchBackground();
				}
				break;
			}
			return false;
		}
		
	}
}
